﻿#include "sysusercontroller.h"

SysUserController::SysUserController()
{
    m_pHelper = DbMgr::instance()->getHelper();

    m_mapFunc.insert("/sys/user/datagrid",      &SysUserController::datagrid);      //获取用户列表
    m_mapFunc.insert("/sys/user/rolebyuserid",  &SysUserController::roleByUserId);  //获取角色信息
    m_mapFunc.insert("/sys/user/save",          &SysUserController::save);          //保存用户信息
    m_mapFunc.insert("/sys/user/delete",        &SysUserController::deleteUser);    //删除用户信息
    m_mapFunc.insert("/sys/user/getname",       &SysUserController::getName);       //获取用户姓名
    m_mapFunc.insert("/sys/user/info",          &SysUserController::info);          //保存基本资料
    m_mapFunc.insert("/sys/user/saveinfo",      &SysUserController::saveInfo);      //获取用户基本资料
    m_mapFunc.insert("/sys/user/savepwd",       &SysUserController::savePwd);       //修改密码
}

void SysUserController::service(HttpRequest& request, HttpResponse& response)
{    
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}


// GET /sys/user/getname?access_token=?
// {"code":0,"data":"管理员","msg":""}
void SysUserController::getName(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));    
    ret.setData(visitUser.getUserName());
    ResponseUtil::replyString(response, ret.toString());
}


// GET /sys/user/info
void SysUserController::info(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    SysDept dept;
    dept.setId(visitUser.getDeptId());
    if(m_pHelper->selectEntityById(&dept))
    {
        ret.setData("deptId", dept.getName());
    }

    ret.setData("id", visitUser.getId());
    ret.setData("userName", visitUser.getUserName());
    ret.setData("realName", visitUser.getRealName());
    ret.setData("headImgUrl", visitUser.getHeadImgUrl());
    ret.setData("sex", visitUser.getSex());
    ret.setData("status", visitUser.getStatus());
    //ret.setData("status", visitUser.getDeptId()); 设置为dictionary状态值
    //ret.setData("deptId", visitUser.getDeptId()); 设置为DeptName
    ret.setData("email", visitUser.getEmail());
    ret.setData("telNo", visitUser.getTelNo());
    ret.setData("userNo", visitUser.getUserNo());
    ret.setData("memo", visitUser.getMemo());
    ResponseUtil::replyJson(response, ret);
}

// GET /sys/user/saveinfo
void SysUserController::saveInfo(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QString realName = request.getParameter("realName");
    QString sex = request.getParameter("sex");
    QString telNo = request.getParameter("telNo");
    QString email = request.getParameter("email");

    if(realName != nullptr && !realName.isEmpty())
        visitUser.setRealName(realName);
    if(sex != nullptr && !sex.isEmpty())
        visitUser.setSex(sex);
    if(telNo != nullptr && !telNo.isEmpty())
        visitUser.setTelNo(telNo);
    if(email != nullptr && !email.isEmpty())
        visitUser.setEmail(email);

    visitUser.setUpdateName(visitUser.getUserName());
    visitUser.setUpdateDate(QDateTime::currentDateTime());

    if(!m_pHelper->updateEntity(&visitUser))
    {
        ret.failedMsg(QStringLiteral("保存失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::UPDATE, QStringLiteral("保存用户"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存用户成功"));
    m_pHelper->insertEntity(&log);
}

void SysUserController::savePwd(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    QString oldPassword = request.getParameter("oldPassword");
    QString password = request.getParameter("password");
    QString repassword = request.getParameter("repassword");

    if(password == oldPassword)
    {
        ret.failedMsg(QStringLiteral("新密码与旧密码相同"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    if(password != repassword)
    {
        ret.failedMsg(QStringLiteral("两次输入密码不一致"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    QString pwdAndSalt = oldPassword + visitUser.getSalt();
    QString oldMd5Pwd = QString(QCryptographicHash::hash(pwdAndSalt.toLocal8Bit(), QCryptographicHash::Md5).toHex());
    if(oldMd5Pwd != visitUser.getPassword())
    {
        ret.failedMsg(QStringLiteral("密码不正确！"));
        response.write(ret.toString().toLocal8Bit());
        return;
    }

    pwdAndSalt = password + visitUser.getSalt();
    QString newMd5Pwd = QString(QCryptographicHash::hash(pwdAndSalt.toLocal8Bit(), QCryptographicHash::Md5).toHex());
    visitUser.setPassword(newMd5Pwd);
    visitUser.setUpdateName(visitUser.getUserName());
    visitUser.setUpdateDate(QDateTime::currentDateTime());

    if(!m_pHelper->updateEntity(&visitUser))
    {
        ret.failedMsg(QStringLiteral("保存失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::UPDATE, QStringLiteral("保存用户"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存用户成功"));
    m_pHelper->insertEntity(&log);
}

//获取用户列表
//http://localhost:9004/sys/user/datagrid?page=1&limit=30&field=createDate&order=desc&access_token=?
//{"code":0,"count":4,"data":[{"createDate":1576820758000,"createName":"admin","deptId":"市场部","email":"442@qq.com","id":"a361c780daefec7ab3ac824dbaf4afbb","memo":"","password":"7eaeb27e613b4e6a692b4bac090c3f8f","realName":"测试5","salt":"5n7MPRQ","sex":"0","status":"1","telNo":"13338800000","updateDate":1576820807000,"updateName":"admin","userName":"test5","userNo":"005","versions":2},{"createDate":1557045230000,"createName":"admin","deptId":"开发1组","email":"212@qq.com","id":"2ab53b87514cd02702c0d471fe7f1ab6","memo":"1","password":"e596700a4ec6b272a91abb0e9966ba24","realName":"xx","salt":"3fQyUE9","sex":"0","status":"1","telNo":"13337785238","updateDate":1574924642000,"updateName":"admin","userName":"xx","userNo":"004","versions":3},{"createDate":1552556416000,"createName":"system","deptId":"众禾集团","email":"2@qq.com","id":"94e270789548580b931e5a0ee66a0b5b","memo":"","password":"5a7d50ad7c5b28f2c6d40a559f0294b2","realName":"张三","salt":"XQIcWe9Jx","sex":"0","status":"1","telNo":"15951172388","updateDate":1553062664000,"updateName":"admin","userName":"zhangsan","userNo":"003","versions":10},{"createDate":1552373720000,"createName":"system","deptId":"开发部","email":"23@qq.com","id":"d4f2018bfc34b5c92942abebff2a829f","memo":"2","password":"abcfdba58b12f7057291edf936f5cbc5","realName":"管理员","salt":"YG","sex":"0","status":"1","telNo":"15951172388","updateDate":1576735066000,"updateName":"admin","userName":"admin","userNo":"001","versions":32}],"msg":""}
void SysUserController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    int page = 1;
    int limit = 20;
    QString field = "createDate";
    QString order = "desc";

    if(request.getParameterMap().contains("page"))
    {
        page = request.getParameter("page").toInt();
    }
    if(request.getParameterMap().contains("limit"))
    {
        limit = request.getParameter("limit").toInt();
    }
    if(request.getParameterMap().contains("field"))
    {
        field = request.getParameter("field");
    }
    if(request.getParameterMap().contains("order"))
    {
        order = request.getParameter("order");
    }

    QList<SysUser> userList;
    int count = 0;
    QStringList condi;
    m_pHelper->getUserList(userList, count, page, limit, condi, field, order=="asc");

    QJsonArray dataArray;
    foreach(SysUser user, userList)
    {
        SysDept dept;
        QJsonObject obj;

        dept.setId(user.getDeptId());
        if(m_pHelper->selectEntityById(&dept))
        {
            obj.insert("deptId", dept.getName());
        }

        obj.insert("id", user.getId());
        obj.insert("userName", user.getUserName());
        obj.insert("realName", user.getRealName());
        obj.insert("headImgUrl", user.getHeadImgUrl());
        obj.insert("status", user.getStatus());
        obj.insert("sex", user.getSex());
        //obj.insert("deptId", user.getDeptId()); 部门名称
        obj.insert("telNo", user.getTelNo());
        obj.insert("userNo", user.getUserNo());
        obj.insert("memo", user.getMemo());

        dataArray.append(obj);
    }

    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", count);
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}

//获取角色信息
//http://localhost:9004/sys/user/roleByUserId?userId=?&access_token=?
//{"code":0,"data":{"roleIds":"?,?","roleNames":"技术人员,销售人员"},"msg":""}
void SysUserController::roleByUserId(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("userId");
    if(idParam.isEmpty())
    {
        ResponseUtil::replyJson(response, ret);
        return;
    }
    int userId = idParam.toInt();

    QStringList condi;
    condi << QString("user_id=%1").arg(userId);
    QList<SysUserRole> userRoleList;
    m_pHelper->getUserRoleList(userRoleList, condi, "");

    QJsonObject obj;
    QStringList roleIdList, roleNameList;
    foreach(SysUserRole userRole, userRoleList)
    {
        SysRole role;
        role.setId(userRole.getRoleId());
        if(m_pHelper->selectEntityById(&role))
        {
            roleIdList << QString::number(role.getId());
            roleNameList << role.getName();
        }
    }
    obj.insert("roleIds", roleIdList.join(","));
    obj.insert("roleNames", roleNameList.join(","));
    ret.setData(obj);
    ResponseUtil::replyJson(response, ret);
}

//保存用户信息
//http://localhost:9004/sys/user/save
/*
id:?
userNo: 005
userName: test5
realName: 测试5
status: 1
deptName: 市场部
deptId:  ?
roleNames: 市场人员
roleIds:  ?
telNo: 13338800000
email: 442@qq.com
sex: 0
memo:
access_token: ?

{"code":0,"success":true,"msg":"操作成功","data":null}
*/
void SysUserController::save(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    SysUser saveUser;
    QString idParam = request.getParameter("id");
    QString roleIds = request.getParameter("roleIds");

    saveUser.setUserNo(request.getParameter("userNo"));
    saveUser.setUserName(request.getParameter("userName"));
    saveUser.setRealName(request.getParameter("realName"));
    saveUser.setStatus(request.getParameter("status"));
//    saveUser.setUserNo(request.getParameter("deptName"));
    saveUser.setDeptId(request.getParameter("deptId").toInt());
    saveUser.setTelNo(request.getParameter("telNo"));
    saveUser.setEmail(request.getParameter("email"));
    saveUser.setSex(request.getParameter("sex"));
    saveUser.setMemo(request.getParameter("memo"));

    //编辑用户
    if(!idParam.isEmpty())
    {
        int userId = idParam.toInt();
        //删除用户角色       
        SysUserRole dao;
        QStringList condi;
        condi << QString("user_id=%1").arg(userId);
        if(!m_pHelper->deleteTable(dao.getTableName(), condi))
        {
            ret.failedMsg(QStringLiteral("删除之前的用户角色失败"));
            ResponseUtil::replyJson(response, ret);
            return;
        }

        //保存用户角色 roleIds
        QStringList roleIdList = roleIds.split(",");
        for(int i=0; i < roleIdList.size(); i++)
        {
            QString roleId = roleIdList.at(i);

            SysUserRole userRole;
            userRole.setCreateDate(QDateTime::currentDateTime());
            userRole.setCreateName(visitUser.getUserName());
            userRole.setUpdateDate(QDateTime::currentDateTime());
            userRole.setUpdateName(visitUser.getUserName());
            userRole.setVersion(1);

            userRole.setUserId(userId);
            userRole.setRoleId(roleId.toInt());

            if(!m_pHelper->insertEntity(&userRole))
            {
                ret.failedMsg(QStringLiteral("保存新的失败"));
                ResponseUtil::replyJson(response, ret);
                return;
            }
        }

        //保存用户
        saveUser.setId(userId);
        saveUser.setUpdateDate(QDateTime::currentDateTime());
        saveUser.setUpdateName(visitUser.getUserName());
        if(!m_pHelper->updateEntity(&saveUser))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            return;
        }
    }
    //新增用户
    else
    {
        //保存用户，设置盐、密码
        saveUser.setSalt(GlobalFunc::getRandomSalt());
        QString password = "123456";
        QString pwdAndSalt = password + saveUser.getSalt();
        QString md5Pwd = QString(QCryptographicHash::hash(pwdAndSalt.toLocal8Bit(), QCryptographicHash::Md5).toHex());
        saveUser.setPassword(md5Pwd);

        saveUser.setCreateDate(QDateTime::currentDateTime());
        saveUser.setCreateName(visitUser.getUserName());
        saveUser.setUpdateDate(QDateTime::currentDateTime());
        saveUser.setUpdateName(visitUser.getUserName());
        saveUser.setVersion(1);
        if(!m_pHelper->insertEntity(&saveUser))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            return;
        }

        //保存用户角色 roleIds
        QStringList roleIdList = roleIds.split(",");
        for(int i=0; i < roleIdList.size(); i++)
        {
            QString roleId = roleIdList.at(i);

            SysUserRole userRole;
            userRole.setCreateDate(QDateTime::currentDateTime());
            userRole.setCreateName(visitUser.getUserName());
            userRole.setUpdateDate(QDateTime::currentDateTime());
            userRole.setUpdateName(visitUser.getUserName());
            userRole.setVersion(1);

            userRole.setUserId(saveUser.getId());
            userRole.setRoleId(roleId.toInt());

            if(!m_pHelper->insertEntity(&userRole))
            {
                ret.failedMsg(QStringLiteral("保存新的失败"));
                ResponseUtil::replyJson(response, ret);
                return;
            }
        }
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::SAVE, QStringLiteral("保存用户"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存用户成功"));
    m_pHelper->insertEntity(&log);
}

//删除用户信息
//http://localhost:9004/sys/user/delete
//{"code":0,"success":true,"msg":"操作成功","data":null}
/*
id:?
access_token: ?
*/
void SysUserController::deleteUser(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString idParam = request.getParameter("id");
    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    int userId = idParam.toInt();
    SysUser delUser;
    delUser.setId(userId);

    //先删除角色
    SysUserRole dao;
    QStringList condi;
    condi << QString("user_id=%1").arg(userId);
    if(!m_pHelper->deleteTable(dao.getTableName(), condi))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    //删除用户
    if(!m_pHelper->deleteEntity(&delUser))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::DEL, QStringLiteral("保存权限菜单"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("保存权限菜单成功"));
    m_pHelper->insertEntity(&log);
}



